/* eslint-disable no-console */
import { all, call, CallEffectFn, Func0, spawn } from 'redux-saga/effects';

export const guardWorkerSaga = (workerSaga: CallEffectFn<Func0>) =>
  function* workerSagaGuard() {
    try {
      yield call(workerSaga);
    } catch (e) {
      console.error('Worker saga failed:', e);
    }
  };

export function* autoResume(sagas: any[], errorHandler?: (err: Error) => void) {
  yield all(
    sagas.map(saga =>
      spawn(function* __spawn_resume___() {
        while (true) {
          try {
            yield call(saga);
            break;
          } catch (err) {
            console.error(err);
            errorHandler && errorHandler(err as Error);
          }
        }
      }),
    ),
  );
}
